package net.xxcl.news.business;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.xxcl.news.pojo.News;
import net.xxcl.news.util.DBConnection;

/**
 * @author Administrator
 * 新闻的业务逻辑类，新闻的所有增、删、改、查等操作
 */
public class NewsBiz {
	
	/**
	 * 根据新闻id查找
	 * @param id
	 * @return
	 */
	public News selectById(int id) {
		DBConnection dbConnection = new DBConnection();
		News news = new News();
		try {					
			String sql = "select * from news where id=?";
			PreparedStatement pstmt = dbConnection.getConnection().prepareStatement(sql);
			pstmt.setInt(1, id);
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()){
				news.setId(id);
				news.setTitle(rs.getString("title"));
				news.setContent(rs.getString("content"));
				news.setAddtime(rs.getDate("addtime"));
				news.setUserid(rs.getInt("userid"));
				news.setTypeid(rs.getInt("typeid"));
			}			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbConnection.close();
		}
		return news;
	}
	
	/**
	 * 查找所有新闻
	 * @return
	 */
	public List<News> selectAllNews() {
		DBConnection dbConnection = new DBConnection();
		List<News> newss = new ArrayList<News>();
		try {					
			String sql = "select * from news";
			PreparedStatement pstmt = dbConnection.getConnection().prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			while(rs.next()){
				News news = new News();
				news.setId(rs.getInt("id"));
				news.setTitle(rs.getString("title"));
				news.setContent(rs.getString("content"));
				news.setAddtime(rs.getDate("addtime"));
				news.setUserid(rs.getInt("userid"));
				news.setTypeid(rs.getInt("typeid"));
				newss.add(news);
			}			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbConnection.close();
		}
		return newss;
	}
	
	/**
	 * 保存一条新闻
	 * @param news
	 * @return
	 */
	public int save(News news) {
		DBConnection dbConnection = new DBConnection();
		int count = 0;
		try {					
			String sql = "insert into news (title,content,addtime,userid,typeid) values(?,?,?,?,?)";
			PreparedStatement pstmt = dbConnection.getConnection().prepareStatement(sql);
			pstmt.setString(1, news.getTitle());
			pstmt.setString(2, news.getContent());
			pstmt.setDate(3, (Date)news.getAddtime());
			pstmt.setInt(4, news.getUserid());
			pstmt.setInt(5, news.getTypeid());
			count = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbConnection.close();
		}
		return count;
	}
	
	/**
	 * 根据id删除一条新闻
	 * @param id
	 * @return
	 */
	public int deleteById(int id){
	
		return 1;
	}
	
	/**
	 * 修改一条新闻
	 * @param news
	 * @return
	 */
	public int update(News news){
		
		return 1;
	}
}
